package org.alvin.gencode;

import com.google.common.base.CaseFormat;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.alvin.gencode.beans.PropConfig;
import org.alvin.gencode.run.code.CodeCond;
import org.alvin.gencode.run.code.Field;
import org.alvin.gencode.run.code.ICodeDao;
import org.alvin.gencode.run.code.Table;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.sql.SQLException;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
public abstract class AbstractService {

    public void genCode(PropConfig propConfig) {
        //读取配置确定需要生成的类
        Path path = Paths.get(propConfig.getConfigDir().concat(File.separator).concat("gcode.rmb"));
        List<String> list = Lists.newArrayList();
        if (Files.exists(path)) {
            try {
                list = Files.readAllLines(path);
                log.info("递增执行,过滤掉数据表:" + list);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        CodeCond codeCond = new CodeCond();
        codeCond.setTableNameNotIn(list);
        try {
            codeCond.setTable_schema(propConfig.getDbName());
            List<Table> tables = this.getCodeDaoByType(propConfig.getDbType()).queryTables(codeCond);
            log.info("表格数量：" + tables.size());
            this.doCreate(tables, propConfig);
            list.addAll(tables.stream().map(Table::getT_name).collect(Collectors.toList()));
            String lines = list.stream().collect(Collectors.joining(System.getProperty("line.separator")));
            Files.write(path, lines.getBytes("utf-8"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

   public List<Field> getFields(Table table ,PropConfig propConfig) throws SQLException {
       //用工参数
       CodeCond codeCond = new CodeCond();
       codeCond.setT_name_eq(table.getT_name());
       codeCond.setTable_schema(propConfig.getDbName());

      return  getCodeDaoByType(propConfig.getDbType()).queryFields(codeCond).stream().map(item -> {
           item.setLower_camel(CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, item.getName()));
           item.setUpper_camel(CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, item.getName()));
           if (item.getAllTypeName().indexOf(".") != -1) {
               int index = item.getAllTypeName().lastIndexOf(".");
               item.setType(item.getAllTypeName().substring(index + 1));
           } else {
               item.setType(item.getAllTypeName());
           }
           return item;
       }).collect(Collectors.toList());


   }

    public abstract void doCreate(List<Table> tables, PropConfig propConfig) throws IOException, SQLException;

    public abstract ICodeDao getCodeDaoByType(String dbType);

}
